'use strict'

var React = require('react-native');
var {msg} = require('iflux-native');
var screen = require('Dimensions').get('window');
var SCREEN_WIDTH = screen.width;
var SCREEN_HEIGHT = screen.height;

var {
	View,
	Image,
	Platform,
	Animated,
	StyleSheet,
	TouchableOpacity
	} = React;

// android底部有遮挡先固定往上移20px,后续优化方案
var paddingBottomValue = Platform.OS === 'ios' ? 0 : 20;

var PopUp = React.createClass({

	getDefaultProps() {
		return {
			height: SCREEN_HEIGHT * 3/4,
			component: null,
			closeStyle: null
		}
	},


	getInitialState() {
		return {
			topValue: new Animated.Value(SCREEN_HEIGHT),
			opacityValue: new Animated.Value(0),
		}
	},


	componentDidMount() {

		Animated.parallel([
			Animated.spring(
				this.state.topValue,
				{toValue: SCREEN_HEIGHT - this.props.height - paddingBottomValue, tension: 15}
			),

			Animated.timing(
				this.state.opacityValue,
				{toValue: 0.5, tension: -100}
			)]
		).start();

		msg.on('pop-up-close', this._handleOnClose);
	},


	componentWillUnmount(){
		msg.removeListener('pop-up-close', this._handleOnClose);
	},


	render() {
		return (
			<View style={styles.container}>
				<Animated.View style={[styles.header, {opacity: this.state.opacityValue}]}/>

				<Animated.View style={[styles.content, {height: this.props.height, top: this.state.topValue}]}>
					{this.props.component}

					{/*关闭按钮*/}
					<TouchableOpacity
						style={styles.closeBtn}
						onPress={this._handleOnClose}>
						<Image
							source={require('img/close_red.png')}
							style={styles.img}
						/>
					</TouchableOpacity>
				</Animated.View>
			</View>
		)
	},


	_handleOnClose() {
		Animated.parallel([
			Animated.spring(
				this.state.topValue,
				{toValue: SCREEN_HEIGHT, tension: 15}
			),
			Animated.timing(
				this.state.opacityValue,
				{toValue: 0, tension: -100}
			)]
		).start((res) => {
			if (res.finished) {
				this.props.onClose();
			}
		})
	}

});

var styles = StyleSheet.create({
	container: {
		top: 0,
		position: 'absolute',
		backgroundColor: 'transparent',
	},
	header: {
		height: SCREEN_HEIGHT,
		width: SCREEN_WIDTH,
		backgroundColor: '#000'
	},
	content: {
		position: 'absolute',
		width: SCREEN_WIDTH,
		backgroundColor: '#fff',
	},
	closeBtn: {
		position: 'absolute',
		top: 0,
		paddingTop: 15,
		right: 0,
		paddingLeft: 10,
		paddingRight: 10
	},
	closeBtnAndroid: {
		position: 'absolute',
		top: 0,
		paddingTop: 5,
		right: 0,
		paddingLeft: 10,
		paddingRight: 10
	},
	img: {
		width: 20,
		height: 20
	}
})

module.exports = PopUp;